package com.chuanke.ckfamily.service.util;



import java.util.HashMap;
import java.util.Map;



import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weijie.core.util.StringUtils;

/**
  * 判断一个用户的Ip地址是否为中国
  * @author xiaoxia
  *
  */
public class IpUtil {
	/**
	 * 阿里云ip所有地址
	 */
	private static final String host = "https://dm-81.data.aliyun.com";
    /**
     * ip请求url
     */
	private static final String path = "/rest/160601/ip/getIpInfo.json";
    /**
     * 请求方式
     */
	private static final String method = "GET";
	/**
	 * 
	 */
	private static final String appcode = "80efbfe434784a1ea5d2e8d6cc5bfc3e";

	private static Logger log = LoggerFactory.getLogger(IpUtil.class);
    
	private static Map<String,String> headers = new HashMap<String,String>();
	private static Map<String,String> querys = new HashMap<String,String>();
	
	public static String getIpInfo(String ip) throws Exception{
		headers.put("Authorization", "APPCODE " + appcode);
		querys.put("ip", ip);
		HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
		
		log.debug("getIpInfo==========>"+response.getStatusLine());
		return EntityUtils.toString(response.getEntity());
	}

	 public static boolean isChinaIp(String ip) throws Exception{
		 int time = 0;
		 while (time < 5) {
		 	try {
		 		time++;
				String ipInfo = getIpInfo(ip);
				if (StringUtils.isEmpty(ipInfo)) {
					continue;
				}

				log.debug("isChinaIP =======> ipInfo={}", ipInfo);
				JSONObject object = JSON.parseObject(ipInfo);
				String code = object.getString("code");
				if(!"0".equals(code)) {
					Thread.sleep(1000);
					continue;
				}

				String country = object.getJSONObject("data").getString("country");
				return "中国".equals(country);
			} catch (Exception e) {
		 		e.printStackTrace();
		 		Thread.sleep(1000);
			}
		 }

		 return false;
	 }

	 public static void main(String[] args) throws Exception {
		System.out.println(getIpInfo("49.65.251.163"));
	}
	
}
